﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
    public static partial class user
    {
        public static dynamic getUserRank(string username)
        {
            var sql = new Sql.SqlDataContext();
            var u = sql.User.FirstOrDefault(row => row.username.ToLower() == username.ToLower() && !row.disabled);
            if (u == null) return new
                {
                    success = false,
                    msg = "用户不存在"
                };

            var us = sql.UserStatistics.First(row => row.username == u.username);
            var problemAccept = sql.Solve.Count(row => row.username == u.username && row.accept > 0);
            /*var rank = (from u2 in sql.User
                        where !u2.disabled
                        from us2 in sql.UserStatistics
                        where us2.username == u2.username
                        let pac2 = sql.Solve.Count(s2 => s2.username == u2.username && s2.accept > 0)
                        where pac2 > problemAccept || pac2 == problemAccept && us2.submit < us.submit
                        select u2).Count() + 1;*/
            var point = (from u2 in sql.User
                         where !u2.disabled
                         from us2 in sql.UserStatistics
                         where us2.username == u2.username
                         let pac2 = sql.Solve.Count(s2 => s2.username == u2.username && s2.accept > 0)
                         where pac2 > problemAccept || pac2 == problemAccept &&
                         (us2.submit < us.submit || us2.submit == us.submit &&
                         u2.regTime < u.regTime)
                         select u2).Count();
            return new
            {
                success = true,
                username = u.username,
                //rank,
                point
            };
        }
    }
}
